import base64
import time

from Crypto.Cipher import AES

# 初始化密钥
key_values = #这里放上密钥
key_bytes = b''
for value in key_values:
    key_bytes += value.to_bytes(4, byteorder='big')
    pass

def getAuthToken(token):
    timestamp = int(time.time() * 1000)
    token2 = f'{{"token":"{token}","platform":3,"version":"2.0.5","device":"FAAE6E21-013F-42D1-B722-599DE3DC340F","timestamp":{timestamp}}}'
    return token2
# 加密函数
def encode(string, key_data=key_bytes):
    # 确保字符串是字节类型
    if isinstance(string, str):
        string = string.encode('utf-8')

    # 使用PKCS7填充
    padder = lambda s: s + (AES.block_size - len(s) % AES.block_size) * chr(
        AES.block_size - len(s) % AES.block_size).encode()
    padded_data = padder(string)

    # 创建AES加密器
    cipher = AES.new(key_data, AES.MODE_ECB)

    # 加密数据
    encrypted_data = cipher.encrypt(padded_data)

    # 转换为base64编码
    return base64.b64encode(encrypted_data).decode('utf-8')


# 解密函数
def decode(encrypted_string, key_data=key_bytes):
    try:
        # 确保加密字符串是字节类型
        if isinstance(encrypted_string, str):
            encrypted_bytes = base64.b64decode(encrypted_string)
        else:
            encrypted_bytes = base64.b64decode(encrypted_string.decode('utf-8'))

        # 创建AES解密器
        cipher = AES.new(key_data, AES.MODE_ECB)

        # 解密数据
        decrypted_data = cipher.decrypt(encrypted_bytes)

        # 去除填充
        unpadder = lambda s: s[:-s[-1]]
        unpadded_data = unpadder(decrypted_data)

        # 返回解密后的字符串
        return unpadded_data.decode('utf-8')
    except Exception as e:
        print(f"解密错误: {e}")
        return None

